/* Copyright 2011 Thomas R. Mackel (tmackel@gmail.com) */

package com.civtechtracker;

import java.util.Calendar;
import android.content.SharedPreferences;

public class AdClickManager {
	private Calendar lastClick;
	private Calendar now;
	private Integer lastClickYear;
	private Integer lastClickMonth;
	private Integer lastClickDay;
	
	private void init(){
		now = Calendar.getInstance();
		lastClick = Calendar.getInstance();
		lastClick.set(lastClickYear, lastClickMonth, lastClickDay);
	}

	private void loadStateData(SharedPreferences preferences){
		lastClickYear = preferences.getInt("lastClickYear", 0);
		lastClickMonth = preferences.getInt("lastClickMonth", 0);
		lastClickDay = preferences.getInt("lastClickDay", 1);
	} 
	
	private void saveStateData(SharedPreferences preferences){
		SharedPreferences.Editor editor = preferences.edit();
		editor.putInt("lastClickYear", lastClickYear);
		editor.putInt("lastClickMonth", lastClickMonth);
		editor.putInt("lastClickDay", lastClickDay);
		editor.commit();
	}
	
	private float dateDiff() {
		long c = now.getTimeInMillis();
		long p = lastClick.getTimeInMillis();
		float diff = c - p;
		return diff / (24*60*60*1000);
	}
	
	public Boolean showAd(SharedPreferences preferences){
		this.loadStateData(preferences);
		this.init();
		if (this.dateDiff() > 7){
			return true;
		}
		else{
			return false;
		}
	}
	
	public void setLastClick(SharedPreferences preferences){
		this.loadStateData(preferences);
		this.init();
		lastClickYear = now.get(Calendar.YEAR);
		lastClickMonth = now.get(Calendar.MONTH);
		lastClickDay = now.get(Calendar.DAY_OF_MONTH);
		this.saveStateData(preferences);
	}
}
